package cc.iotkit.screen.dao;

import cc.iotkit.common.satoken.utils.LoginHelper;
import cc.iotkit.screen.dto.Period;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Map;

/***
 * 清扫统计
 */
@Component
public class CleanStatisticsRepositoryImpl implements CleanStatisticsRepository{
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * 示例：
     * 年：/screen/clean_statistics/year/-1
     * 月：/screen/clean_statistics/month/2024
     * 日：/screen/clean_statistics/day/2024-07
     * 周：/screen/clean_statistics/week/7
     * @param period
     * @param date
     * @return
     */
    public List<Map<String,Object>> getStatistics(String period,String date){
        String sql="SELECT %s date,d.`name`,round(sum(square),0) as total\n" +
                "FROM `device_daily_report` a\n" +
                "inner join device_info b on a.device_id=b.device_id\n" +
                "inner join product c on b.product_key=c.product_key\n" +
                "inner join category d on c.category=d.id\n" +
                "WHERE (d.`name`='扫地' or d.`name`='洗地') %s\n" +
                "GROUP BY %s,d.`name`\n" +
                "ORDER BY date";
        String where=tenantPermission();
        String reportDate=period+"(report_date)";
        if(period.equals(Period.Type.year.toString())){
            sql=String.format(sql,reportDate,where,reportDate);
        }else if(period.equals(Period.Type.month.toString())){
            sql=String.format(sql,reportDate,"and year(report_date)='"+date+"'"+where,reportDate);
        }else if(period.equals(Period.Type.day.toString())){
            sql=String.format(sql,reportDate,"and DATE_FORMAT(report_date,'%Y-%m')='"+date+"'"+where,reportDate);
        }else if(period.equals(Period.Type.week.toString())){
            sql=String.format(sql,"DATE_FORMAT(report_date,'%m-%d')","and report_date>=CURDATE() - INTERVAL 7 DAY "+where,"DATE_FORMAT(report_date,'%m-%d')");
        }
        List<Map<String,Object>> result= entityManager.createNativeQuery(sql).unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
                .getResultList();
        return result;
    }

    private String tenantPermission(){
        //超级管理员或系统进程调用
        if(LoginHelper.isSuperAdmin()|| RequestContextHolder.getRequestAttributes()==null)
            return "";
        else {
            return " and b.tenant_id="+LoginHelper.getTenantId();
        }
    }
}
